﻿Imports System.Object
Imports VSModel
Imports Cls_Common
Imports System.IO
Imports SecurityService
Partial Class Control_Contents_Edit_Tip
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function "
    Dim level As String = -1
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            getMenu()
            If Not Request.QueryString("type") Is Nothing Then
                hidType.Value = Request.QueryString("type")

            End If
            If Not Request.QueryString("Id") Is Nothing Then
                hidID.Value = Request.QueryString("Id")
                ShowData()
            End If
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If

            Dim ctrl As System.Web.UI.WebControls.WebControl
            ctrl = txtContent.CreateCommandButton("ask_mask_fullname", "remove_format.gif", "Bỏ định dạng")
            ctrl.Attributes("onclick") = "removeTextFormat('" + txtContent.ClientID + "');"
            'get the pos after the Italic    
            Dim pos As Integer
            pos = txtContent.ToolControls.IndexOf("JustifyRight") + 1
            'add this custom button into the editor    
            txtContent.InsertToolControl(pos, "ask_mask_fullname", ctrl)



        End If

    End Sub
    Protected Sub getMenu()
        drlMenu.Items.Clear()
        Dim data As New VSEntities
        Dim p As List(Of Menu) = (From q In data.Menus Select q).ToList
        drlMenu.DataValueField = "MenuID"
        drlMenu.DataTextField = "Title"
        RecursiveFillTree(p, 0)
        drlMenu.Items.Insert(0, New ListItem("----Chọn Nhánh Tin----", "0"))

    End Sub
    Private Sub RecursiveFillTree(ByVal dtParent As List(Of Menu), ByVal parentID As Integer)
        level += 1
        'on the each call level increment 1
        Dim appender As New StringBuilder()

        For j As Integer = 0 To level - 1

            appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;")
        Next
        If level > 0 Then
            appender.Append("|__")
        End If

        Dim data As New VSEntities
        Dim dv As List(Of Menu) = (From q In data.Menus Where q.ParentId = parentID Select q).ToList
        Dim i As Integer

        If dv.Count > 0 Then
            For i = 0 To dv.Count - 1
                Dim itm As New ListItem(Server.HtmlDecode(appender.ToString() + dv.Item(i).Title.ToString()), dv.Item(i).MenuId.ToString())
                If Check_Selected(dv.Item(i).MenuId) = False Then
                    itm.Attributes.Add("class", "ItemDisabled")
                Else
                    itm.Attributes.Add("class", "ItemActived")
                End If
                drlMenu.Items.Add(itm)
                RecursiveFillTree(dtParent, Integer.Parse(dv.Item(i).MenuId.ToString()))
            Next
        End If

        level -= 1
        'on the each function end level will decrement by 1
    End Sub
    Protected Sub ShowData()
        Using data As New VSEntities
            Dim p = (From q In data.Contents Where q.Id = hidID.Value Select q).SingleOrDefault
            If Not p Is Nothing Then
                txtTitle.Text = IIf(IsNothing(p.Title) = True, "", p.Title)
                txtDescription.Text = IIf(IsNothing(p.Description) = True, "", p.Description)
                txtContent.Text = IIf(IsNothing(p.Contents) = True, "", p.Contents)
                imgUpload.ImageUrl = p.Image
                hidImagePath.Text = IIf(IsNothing(p.Image) = True, "", p.Image.ToString())
                txtAuthor.Text = IIf(IsNothing(p.Author) = True, "", p.Author)
                drlMenu.SelectedValue = IIf(IsNothing(p.MenuId) = True, 0, p.MenuId)
                chkIsHot.Checked = p.IsHot
                Dim strImageBig As String = ""
                If p.IsHot = True Then
                    hidImageBig.Text = IIf(IsNothing(p.ImageBig) = True, "", p.ImageBig)
                    strImageBig += "Change_Assign();showImageBig('" + IIf(IsNothing(p.ImageBig) = True, "", p.ImageBig) + "');"
                End If
                chkIsNew.Checked = p.IsNew
                txtImg.Text = p.URL
                'Show keyword
                Dim obj = (From ck In data.ContentsKeywords Join k In data.Keywords On ck.KeywordId Equals k.KeywordID Where ck.ContentId = p.Id Order By k.Keyword1 Ascending Select New With {.KeyId = ck.KeywordId, .KeyWord = k.Keyword1}).ToList
                For i As Integer = 0 To obj.Count - 1
                    txtKeyword.Text &= obj(i).KeyId & ";"
                    txtStrKeyWord.Text &= obj(i).KeyWord & ";"
                Next

                'Show Subject
                Dim s = (From cs In data.ContentsSubjects Join sb In data.Subjects On cs.SubjectId Equals sb.SubjectId Where cs.ContentId = p.Id Order By sb.Subject1 Ascending Select New With {.KeyId = cs.SubjectId, .Subject = sb.Subject1}).FirstOrDefault
                If (Not s Is Nothing) Then
                    txtSubjectId.Text = s.KeyId & ";"
                    txtSubject.Text = s.Subject & ";"
                End If
                Excute_Javascript("appendOptionLast('" & txtKeyword.Text & "','" & txtStrKeyWord.Text & "','selKeyWord');" & strImageBig, Me.Page, True)

            End If
        End Using

    End Sub



#End Region
#Region "Event for control"


    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim data As New VSEntities
        Dim p = (From q In data.Contents Where q.Id = hidID.Value Select q).SingleOrDefault
        Dim sTitle As String = p.Title
        Dim sQueryString As String = p.QueryString

        Try
            p.Id = hidID.Value
            p.Title = txtTitle.Text.Trim()
            p.Description = txtDescription.Text.Trim()
            p.Contents = txtContent.Text.Trim()
            p.Modified = Date.Now
            p.Modifier = Session("Username")
            p.Image = hidImagePath.Text
            p.Author = txtAuthor.Text.Trim
            If drlMenu.SelectedValue = 0 Then
                p.MenuId = Nothing
            Else
                p.MenuId = CInt(drlMenu.SelectedValue)
            End If
            p.QueryString = makeURLFriendly(txtTitle.Text.Trim)
            p.IsHot = IIf(chkIsHot.Checked = True, True, False)
            If p.IsHot = True Then
                p.ImageBig = hidImageBig.Text.Trim
            Else
                p.ImageBig = Nothing
            End If
            p.IsNew = IIf(chkIsNew.Checked = True, True, False)
            'Delete keyword
            Dim obj = (From ck In data.ContentsKeywords Where ck.ContentId = p.Id Select ck).ToList
            If (Not obj Is Nothing AndAlso obj.Count > 0) Then
                For i As Integer = 0 To obj.Count - 1
                    Dim iCid As Integer = obj(i).ContentId
                    Dim iKid As Integer = obj(i).KeywordId
                    Dim o = (From cok In data.ContentsKeywords Where cok.ContentId = iCid And cok.KeywordId = iKid Select cok).FirstOrDefault
                    data.ContentsKeywords.DeleteObject(o)
                    Dim h = (From g In data.Keywords Where g.KeywordID = o.KeywordId Select g).FirstOrDefault
                    h.Viewed = (IIf(IsNothing(h.Viewed) = True, 0, h.Viewed) - 1)

                    data.SaveChanges()
                Next
            End If
            RemoveKeyWordJavascript(sTitle & ";" & sQueryString)

            'Insert keyword
            Dim arrKeyWord As String() = txtKeyword.Text.TrimEnd(";").Split(";")
            If arrKeyWord.Length > 1 Then


                For i As Integer = 0 To arrKeyWord.Length - 1
                    Dim kw As New ContentsKeyword
                    kw.ContentId = hidID.Value
                    kw.KeywordId = arrKeyWord(i)
                    data.ContentsKeywords.AddObject(kw)
                    Dim h = (From g In data.Keywords Where g.KeywordID = kw.KeywordId Select g).FirstOrDefault
                    h.Viewed = (IIf(IsNothing(h.Viewed) = True, 0, h.Viewed) + 1)

                Next
            End If
            data.SaveChanges()
            AddKeyWordJavascript(txtTitle.Text & ";" & makeURLFriendly(txtTitle.Text.Trim))

            'Delete Subject of contents
            Dim objS = (From s In data.ContentsSubjects Where s.ContentId = p.Id Select s).FirstOrDefault
            If (Not objS Is Nothing) Then
                data.ContentsSubjects.DeleteObject(objS)
                data.SaveChanges()
            End If

            'Insert Subject
            If txtSubjectId.Text.Trim.TrimEnd(";") <> 0 Then
                Dim q As New ContentsSubject
                q.ContentId = hidID.Value
                q.SubjectId = txtSubjectId.Text.Trim.TrimEnd(";")
                data.ContentsSubjects.AddObject(q)
                data.SaveChanges()
            End If

            Insert_App_Log("Edit Contents:" & txtTitle.Text.Trim & "", Function_Name.Content, Audit_Type.Edit, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
            Excute_Javascript("Alertbox('Lưu dữ liệu thành công.');window.location ='../../Page/Contents/List.aspx?MenuId=" & drlMenu.SelectedValue & "';", Me.Page, True)
            'Response.Redirect("List.aspx?MenuId=" & drlMenu.SelectedValue)
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()
            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)

            Excute_Javascript("Alertbox('Cập nhật dữ liệu thất bại.');", Me.Page, True)
        End Try
        data = Nothing
    End Sub
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx?MenuId=" & drlMenu.SelectedValue)
    End Sub
#End Region
    Protected Sub hplSelKeyWord_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplSelKeyWord.Init
        hplSelKeyWord.CssClass = "thickbox"
        hplSelKeyWord.NavigateUrl = "~/Page/KeyWord/KeyWord.aspx?keepThis=true&TB_iframe=true&height=450&width=350&modal=true"
    End Sub

    Protected Sub hplSelSubject_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplSelSubject.Init
        hplSelSubject.CssClass = "thickbox"
        hplSelSubject.NavigateUrl = "~/Page/Subject/Subject.aspx?keepThis=true&TB_iframe=true&height=450&width=400&modal=true"
    End Sub
End Class
